//验证标签是否存在
const service = require("../services/label.service");
const errorType = require("../constant/errTypes");
const verifyLabelExists = async (ctx, next) => {
  console.log("验证动态中是否已有标签verifyLabelExists");
  const {labels} = ctx.request.body;
  const newLabels = [];
  for (let name of labels) {
    const labelResult = await service.getLabelByName(name);
    const label = {name}
    if (labelResult.length === 0) {
      const result = await service.createLabel(name);
      label.id = result.insertId;
      newLabels.push(label);
    } else {
      label.id = labelResult[0].id;
      newLabels.push(label);
    }
  }
  ctx.labels = newLabels;//将新的标签放入ctx中  后续的操作可以直接使用 不用再次查询  减少数据库查询次数   可以提高性能
  await next();
}
module.exports = {
  verifyLabelExists
}